<template>
  <div class="same-odds-analysis-page">
    <!-- 页面标题 -->
    <el-card class="title-card" shadow="never">
      <div class="page-title">
        <h2>{{ pageTitle }}</h2>
        <el-button type="text" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
    </el-card>

    <!-- 队伍实力分析结果 -->
    <TeamStrengthAnalysis :teamStrengthAnalysisData="teamStrengthAnalysisData" />
<!-- 球员实力分析结果 -->
    <PlayerStrengthAnalysis
      :playerStrengthAnalysisData="playerStrengthAnalysisData"
      @data-updated="handlePlayerDataUpdate"
    />
    <!-- 爆冷分析结果 -->
    <ColdPlayAnalysis :coldPlayAnalysisData="coldPlayAnalysisData" />

    

    <!-- 赔率范围设置 -->
    <OddsRangeSettings
      v-model:rangeValues="rangeValues"
      :originalValues="originalValues"
      @reset="resetRangeInputs"
      @search="searchByRange"
    />

    <!-- 查询按钮 -->
    <el-card class="odds-range-card" shadow="never">
      
        <div class="query-button-wrapper">
          <el-button
            type="primary"
            size="large"
            @click="querySameOddsAnalysis"
            :loading="sameOddsAnalysisLoading"
          >   
            查询同赔
          </el-button>
      
      </div>
    </el-card>

    <!-- 比赛历史分析结果 -->
    <MatchHistoryAnalysis 
      :sameOddsAnalysisResult="sameOddsAnalysisResult"
      :matchDetailsData="matchDetailsData"
      :matchDetailsLoading="matchDetailsLoading"
      @remove-match="removeMatch"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { HistoricalSameOddsData, SameOdds168AnalysisStats, ColdPlayAnalysisStats, TeamStrengthAnalysisData, PlayerStrengthAnalysisResponseData } from './apis/type'
import { getColdPlayAnalysisStatsApi, getSameOddsMatchDetailsApi, getTeamStrengthAnalysisApi, getPlayerStrengthAnalysisApi } from './apis'
import { Search, ArrowLeft, Minus, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useTagsViewStore } from '@/pinia/stores/tags-view'

// 导入子组件
import TeamStrengthAnalysis from './components/TeamStrengthAnalysis.vue'
import ColdPlayAnalysis from './components/ColdPlayAnalysis.vue'
import OddsRangeSettings from './components/OddsRangeSettings.vue'
import MatchHistoryAnalysis from './components/MatchHistoryAnalysis.vue'
import PlayerStrengthAnalysis from './components/PlayerStrengthAnalysis.vue'

const router = useRouter()
const route = useRoute()
const tagsViewStore = useTagsViewStore()

// 响应式数据
const sameOddsAnalysisLoading = ref(false)
const sameOddsAnalysisResult = ref<SameOdds168AnalysisStats | null>(null)
const currentMatchForAnalysis = ref<HistoricalSameOddsData | null>(null)
const coldPlayAnalysisData = ref<{
  home: ColdPlayAnalysisStats | null,
  away: ColdPlayAnalysisStats | null
} | null>(null)
const coldPlayAnalysisLoading = ref(false)

// 队伍实力分析数据
const teamStrengthAnalysisData = ref<{
  home: TeamStrengthAnalysisData | null,
  away: TeamStrengthAnalysisData | null
} | null>(null)
const teamStrengthAnalysisLoading = ref(false)

// 球员实力分析数据
const playerStrengthAnalysisData = ref<{
  home: PlayerStrengthAnalysisResponseData | null,
  away: PlayerStrengthAnalysisResponseData | null
} | null>(null)
const playerStrengthAnalysisLoading = ref(false)

// 比赛明细数据
const matchDetailsData = ref<HistoricalSameOddsData[]>([])
const matchDetailsLoading = ref(false)

// 赔率范围控制对象 - values must match the units used in originalOddsValues (percentages for prob/return rate)
const rangeValues = ref({
  homeInitialMin: 1.0,
  homeInitialMax: 10.0,
  drawInitialMin: 1.0,
  drawInitialMax: 10.0,
  awayInitialMin: 1.0,
  awayInitialMax: 10.0,

  homeFinalMin: 1.0,
  homeFinalMax: 10.0,
  drawFinalMin: 1.0,
  drawFinalMax: 10.0,
  awayFinalMin: 1.0,
  awayFinalMax: 10.0,

  probHomeInitialMin: 0.0,  // percentage values (0-100)
  probHomeInitialMax: 100.0,
  probDrawInitialMin: 0.0,
  probDrawInitialMax: 100.0,
  probAwayInitialMin: 0.0,
  probAwayInitialMax: 100.0,

  probHomeFinalMin: 0.0,
  probHomeFinalMax: 100.0,
  probDrawFinalMin: 0.0,
  probDrawFinalMax: 100.0,
  probAwayFinalMin: 0.0,
  probAwayFinalMax: 100.0,

  returnRateInitialMin: 0.0,  // percentage values (0-100)
  returnRateInitialMax: 100.0,
  returnRateFinalMin: 0.0,
  returnRateFinalMax: 100.0
});

// 原始赔率值（用于设置默认范围）
const originalOddsValues = computed(() => {
  if (!currentMatchForAnalysis.value) {
    return null;
  }

  // 从当前比赛获取原始赔率数据
  const match = currentMatchForAnalysis.value;

  // 使用初始和最终赔率数据
  const homeInitial = match.home_initial || 2.5;
  const drawInitial = match.draw_initial || 3.0;
  const awayInitial = match.away_initial || 2.8;

  // 使用最终赔率数据
  const homeFinal = match.home_final || homeInitial;
  const drawFinal = match.draw_final || drawInitial;
  const awayFinal = match.away_final || awayInitial;

  // 使用已计算好的概率数据，如果没有则基于赔率计算
  const probHomeInitial = match.prob_home_initial || (homeInitial ? 1 / homeInitial : 0.4);
  const probDrawInitial = match.prob_draw_initial || (drawInitial ? 1 / drawInitial : 0.333);
  const probAwayInitial = match.prob_away_initial || (awayInitial ? 1 / awayInitial : 0.267);

  const probHomeFinal = match.prob_home_final || (homeFinal ? 1 / homeFinal : 0.4);
  const probDrawFinal = match.prob_draw_final || (drawFinal ? 1 / drawFinal : 0.333);
  const probAwayFinal = match.prob_away_final || (awayFinal ? 1 / awayFinal : 0.267);

  // 使用已计算好的返还率数据，如果没有则计算
  const returnRateInitial = match.return_rate_initial ||
    ((homeInitial && drawInitial && awayInitial) ? 1 / (1/homeInitial + 1/drawInitial + 1/awayInitial) : 0.95);

  const returnRateFinal = match.return_rate_final ||
    ((homeFinal && drawFinal && awayFinal) ? 1 / (1/homeFinal + 1/drawFinal + 1/awayFinal) : 0.95);

  return {
    homeInitial,
    drawInitial,
    awayInitial,
    homeFinal,
    drawFinal,
    awayFinal,
    probHomeInitial: probHomeInitial * 100, // Convert to percentage for display
    probDrawInitial: probDrawInitial * 100,
    probAwayInitial: probAwayInitial * 100,
    probHomeFinal: probHomeFinal * 100,
    probDrawFinal: probDrawFinal * 100,
    probAwayFinal: probAwayFinal * 100,
    returnRateInitial: returnRateInitial * 100, // Convert to percentage for display
    returnRateFinal: returnRateFinal * 100
  };
});

// 原始值（用于OddsRangeSettings组件）
const originalValues = computed(() => {
  if (!originalOddsValues.value) {
    // 如果没有原始赔率值，返回默认值
    return {
      homeInitial: 2.5,
      drawInitial: 3.0,
      awayInitial: 2.8,
      homeFinal: 2.5,
      drawFinal: 3.0,
      awayFinal: 2.8,
      probHomeInitial: 40.0,
      probDrawInitial: 33.3,
      probAwayInitial: 26.7,
      probHomeFinal: 40.0,
      probDrawFinal: 33.3,
      probAwayFinal: 26.7,
      returnRateInitial: 95.0,
      returnRateFinal: 95.0
    };
  }

  // 使用原始赔率值设置范围
  const {
    homeInitial, drawInitial, awayInitial,
    homeFinal, drawFinal, awayFinal,
    probHomeInitial, probDrawInitial, probAwayInitial,
    probHomeFinal, probDrawFinal, probAwayFinal,
    returnRateInitial, returnRateFinal
  } = originalOddsValues.value;

  return {
    homeInitial,
    drawInitial,
    awayInitial,
    homeFinal,
    drawFinal,
    awayFinal,
    probHomeInitial,
    probDrawInitial,
    probAwayInitial,
    probHomeFinal,
    probDrawFinal,
    probAwayFinal,
    returnRateInitial,
    returnRateFinal
  };
});

// 页面标题
const pageTitle = computed(() => {
  if (!currentMatchForAnalysis.value) return '同赔分析'
  const match = currentMatchForAnalysis.value
  const homeScore = match.homescore !== null ? match.homescore : '-'
  const awayScore = match.awayscore !== null ? match.awayscore : '-'
  return `${match.homesxname} ${homeScore} - ${awayScore} ${match.awaysxname}`
})


// 方法
function goBack() {
  router.push('/odds/same-europe-168')
}

// 格式化赔率显示
function formatOdds(value: number | null | undefined): string {
  if (value === null || value === undefined) {
    return '-'
  }
  // 保留3位小数
  return value.toFixed(3)
}

// 删除比赛并重新计算同赔分析结果
function removeMatch(row: HistoricalSameOddsData) {
  // 从matchDetailsData中移除该行
  const index = matchDetailsData.value.findIndex(item => item.fid === row.fid);
  if (index !== -1) {
    matchDetailsData.value.splice(index, 1);

    // 重新计算同赔分析结果
    recalculateSameOddsAnalysis();
  }
}

// 重新计算同赔分析结果
function recalculateSameOddsAnalysis() {
  const data = matchDetailsData.value;
  const total_matches = data.length;
  let home_wins = 0;
  let draws = 0;
  let away_wins = 0;

  // 用于统计比分出现次数
  const scoreCounts: Record<string, number> = {};
  const homeWinScoreCounts: Record<string, number> = {}; // 主胜比分统计
  const awayWinScoreCounts: Record<string, number> = {}; // 客胜比分统计

  // 遍历所有比赛数据进行统计
  for (const match of data) {
    // 统计胜负平结果
    if (match.homescore !== null && match.awayscore !== null) {
      const score = `${match.homescore}-${match.awayscore}`;
      scoreCounts[score] = (scoreCounts[score] || 0) + 1;

      if (match.homescore > match.awayscore) {
        home_wins++;
        // 主胜比分统计
        homeWinScoreCounts[score] = (homeWinScoreCounts[score] || 0) + 1;
      } else if (match.homescore === match.awayscore) {
        draws++;
      } else {
        away_wins++;
        // 客胜比分统计
        awayWinScoreCounts[score] = (awayWinScoreCounts[score] || 0) + 1;
      }
    }
  }

  // 计算胜率
  const home_win_rate = total_matches > 0 ? (home_wins / total_matches) * 100 : 0;
  const draw_rate = total_matches > 0 ? (draws / total_matches) * 100 : 0;
  const away_win_rate = total_matches > 0 ? (away_wins / total_matches) * 100 : 0;

  // 找出最常见的三个比分
  const sortedScores = Object.entries(scoreCounts)
    .sort((a, b) => b[1] - a[1]);

  const most_common_score = sortedScores[0] ? sortedScores[0][0] : null;
  const second_most_common_score = sortedScores[1] ? sortedScores[1][0] : null;
  const third_most_common_score = sortedScores[2] ? sortedScores[2][0] : null;

  // 找出主胜的三个常见比分
  const sortedHomeWinScores = Object.entries(homeWinScoreCounts)
    .sort((a, b) => b[1] - a[1]);

  const home_win_most_common_score = sortedHomeWinScores[0] ? sortedHomeWinScores[0][0] : null;
  const home_win_second_most_common_score = sortedHomeWinScores[1] ? sortedHomeWinScores[1][0] : null;
  const home_win_third_most_common_score = sortedHomeWinScores[2] ? sortedHomeWinScores[2][0] : null;

  // 找出客胜的三个常见比分
  const sortedAwayWinScores = Object.entries(awayWinScoreCounts)
    .sort((a, b) => b[1] - a[1]);

  const away_win_most_common_score = sortedAwayWinScores[0] ? sortedAwayWinScores[0][0] : null;
  const away_win_second_most_common_score = sortedAwayWinScores[1] ? sortedAwayWinScores[1][0] : null;
  const away_win_third_most_common_score = sortedAwayWinScores[2] ? sortedAwayWinScores[2][0] : null;

  // 更新同赔分析结果
  sameOddsAnalysisResult.value = {
    total_matches,
    home_wins,
    draws,
    away_wins,
    home_win_rate,
    draw_rate,
    away_win_rate,
    most_common_score,
    second_most_common_score,
    third_most_common_score,
    home_win_most_common_score,
    home_win_second_most_common_score,
    home_win_third_most_common_score,
    away_win_most_common_score,
    away_win_second_most_common_score,
    away_win_third_most_common_score
  };
}

// 重置范围输入
function resetRangeInputs() {
  // 重置范围值为默认值
  rangeValues.value = {
    homeInitialMin: 1.0,
    homeInitialMax: 10.0,
    drawInitialMin: 1.0,
    drawInitialMax: 10.0,
    awayInitialMin: 1.0,
    awayInitialMax: 10.0,

    homeFinalMin: 1.0,
    homeFinalMax: 10.0,
    drawFinalMin: 1.0,
    drawFinalMax: 10.0,
    awayFinalMin: 1.0,
    awayFinalMax: 10.0,

    probHomeInitialMin: 0.0,
    probHomeInitialMax: 100.0,
    probDrawInitialMin: 0.0,
    probDrawInitialMax: 100.0,
    probAwayInitialMin: 0.0,
    probAwayInitialMax: 100.0,

    probHomeFinalMin: 0.0,
    probHomeFinalMax: 100.0,
    probDrawFinalMin: 0.0,
    probDrawFinalMax: 100.0,
    probAwayFinalMin: 0.0,
    probAwayFinalMax: 100.0,

    returnRateInitialMin: 0.0,
    returnRateInitialMax: 100.0,
    returnRateFinalMin: 0.0,
    returnRateFinalMax: 100.0
  };
}

// 更新赔率范围（由于使用了计算属性，这个方法可以是空的）
function updateOddsRanges() {
  // 计算属性会自动更新，这里不需要额外操作
}

// 按范围搜索函数
function searchByRange() {
  // 可以在这里执行基于范围的搜索逻辑
  console.log('按范围搜索:', rangeValues.value);
  // 这里可以添加具体搜索逻辑
}

// 查询同赔分析
async function querySameOddsAnalysis() {
  if (!currentMatchForAnalysis.value) {
    ElMessage.error('请先选择比赛')
    return
  }

  sameOddsAnalysisLoading.value = true
  coldPlayAnalysisLoading.value = true
  matchDetailsLoading.value = true

  try {
    const match = currentMatchForAnalysis.value

    // 构造比赛明细请求参数
    const matchDetailsRequestData = {
      event_name: match.event_name || null,
      status:'4',
      // matchtime_s: match.matchtime ? (() => {
      //   const date = new Date(match.matchtime.split('T')[0]);
      //   date.setDate(date.getDate() - 365); // 查询过去一年的比赛
      //   return date.toISOString().split('T')[0];
      // })() : null,
      matchtime_e: match.matchtime ? (() => {
        const date = new Date(match.matchtime.split('T')[0]);
        date.setDate(date.getDate() - 1);
        return date.toISOString().split('T')[0];
      })() : null,

      // 初始赔率范围
      home_initial_min: rangeValues.value.homeInitialMin,
      home_initial_max: rangeValues.value.homeInitialMax,
      draw_initial_min: rangeValues.value.drawInitialMin,
      draw_initial_max: rangeValues.value.drawInitialMax,
      away_initial_min: rangeValues.value.awayInitialMin,
      away_initial_max: rangeValues.value.awayInitialMax,

      // 临场赔率范围
      home_final_min: rangeValues.value.homeFinalMin,
      home_final_max: rangeValues.value.homeFinalMax,
      draw_final_min: rangeValues.value.drawFinalMin,
      draw_final_max: rangeValues.value.drawFinalMax,
      away_final_min: rangeValues.value.awayFinalMin,
      away_final_max: rangeValues.value.awayFinalMax,

      // 初始概率范围 (convert percentages to decimals)
      prob_home_initial_min: rangeValues.value.probHomeInitialMin ? rangeValues.value.probHomeInitialMin / 100 : null,
      prob_home_initial_max: rangeValues.value.probHomeInitialMax ? rangeValues.value.probHomeInitialMax / 100 : null,  
      prob_draw_initial_min: rangeValues.value.probDrawInitialMin ? rangeValues.value.probDrawInitialMin / 100 : null,
      prob_draw_initial_max: rangeValues.value.probDrawInitialMax ? rangeValues.value.probDrawInitialMax / 100 : null,
      prob_away_initial_min: rangeValues.value.probAwayInitialMin ? rangeValues.value.probAwayInitialMin / 100 : null,
      prob_away_initial_max: rangeValues.value.probAwayInitialMax ? rangeValues.value.probAwayInitialMax / 100 : null,

      // 临场概率范围 (convert percentages to decimals)
      prob_home_final_min: rangeValues.value.probHomeFinalMin ? rangeValues.value.probHomeFinalMin / 100 : null,
      prob_home_final_max: rangeValues.value.probHomeFinalMax ? rangeValues.value.probHomeFinalMax / 100 : null,
      prob_draw_final_min: rangeValues.value.probDrawFinalMin ? rangeValues.value.probDrawFinalMin / 100 : null,
      prob_draw_final_max: rangeValues.value.probDrawFinalMax ? rangeValues.value.probDrawFinalMax / 100 : null,
      prob_away_final_min: rangeValues.value.probAwayFinalMin ? rangeValues.value.probAwayFinalMin / 100 : null,
      prob_away_final_max: rangeValues.value.probAwayFinalMax ? rangeValues.value.probAwayFinalMax / 100 : null,

      // 初始返还率范围 (convert percentages to decimals)
      return_rate_initial_min: rangeValues.value.returnRateInitialMin ? rangeValues.value.returnRateInitialMin / 100 : null,
      return_rate_initial_max: rangeValues.value.returnRateInitialMax ? rangeValues.value.returnRateInitialMax / 100 : null,

      // 临场返还率范围 (convert percentages to decimals)
      return_rate_final_min: rangeValues.value.returnRateFinalMin ? rangeValues.value.returnRateFinalMin / 100 : null,
      return_rate_final_max: rangeValues.value.returnRateFinalMax ? rangeValues.value.returnRateFinalMax / 100 : null,

      current_page: 1,
      page_size: 100
    }

    // 查询比赛明细数据
    const matchDetailsResponse = await getSameOddsMatchDetailsApi(matchDetailsRequestData)

    // 根据比赛明细数据计算同赔分析结果
    if (matchDetailsResponse.code === 0 && matchDetailsResponse.data) {
      matchDetailsData.value = matchDetailsResponse.data

      // 计算同赔分析统计结果
      const data = matchDetailsResponse.data
      const total_matches = data.length
      let home_wins = 0
      let draws = 0
      let away_wins = 0

      // 用于统计比分出现次数
      const scoreCounts: Record<string, number> = {}
      const homeWinScoreCounts: Record<string, number> = {} // 主胜比分统计
      const awayWinScoreCounts: Record<string, number> = {} // 客胜比分统计

      // 遍历所有比赛数据进行统计
      for (const match of data) {
        // 统计胜负平结果
        if (match.homescore !== null && match.awayscore !== null) {
          const score = `${match.homescore}-${match.awayscore}`
          scoreCounts[score] = (scoreCounts[score] || 0) + 1

          if (match.homescore > match.awayscore) {
            home_wins++
            // 主胜比分统计
            homeWinScoreCounts[score] = (homeWinScoreCounts[score] || 0) + 1
          } else if (match.homescore === match.awayscore) {
            draws++
          } else {
            away_wins++
            // 客胜比分统计
            awayWinScoreCounts[score] = (awayWinScoreCounts[score] || 0) + 1
          }
        }
      }

      // 计算胜率
      const home_win_rate = total_matches > 0 ? (home_wins / total_matches) * 100 : 0
      const draw_rate = total_matches > 0 ? (draws / total_matches) * 100 : 0
      const away_win_rate = total_matches > 0 ? (away_wins / total_matches) * 100 : 0

      // 找出最常见的三个比分
      const sortedScores = Object.entries(scoreCounts)
        .sort((a, b) => b[1] - a[1])

      const most_common_score = sortedScores[0] ? sortedScores[0][0] : null
      const second_most_common_score = sortedScores[1] ? sortedScores[1][0] : null
      const third_most_common_score = sortedScores[2] ? sortedScores[2][0] : null

      // 找出主胜的三个常见比分
      const sortedHomeWinScores = Object.entries(homeWinScoreCounts)
        .sort((a, b) => b[1] - a[1]);

      const home_win_most_common_score = sortedHomeWinScores[0] ? sortedHomeWinScores[0][0] : null;
      const home_win_second_most_common_score = sortedHomeWinScores[1] ? sortedHomeWinScores[1][0] : null;
      const home_win_third_most_common_score = sortedHomeWinScores[2] ? sortedHomeWinScores[2][0] : null;

      // 找出客胜的三个常见比分
      const sortedAwayWinScores = Object.entries(awayWinScoreCounts)
        .sort((a, b) => b[1] - a[1]);

      const away_win_most_common_score = sortedAwayWinScores[0] ? sortedAwayWinScores[0][0] : null;
      const away_win_second_most_common_score = sortedAwayWinScores[1] ? sortedAwayWinScores[1][0] : null;
      const away_win_third_most_common_score = sortedAwayWinScores[2] ? sortedAwayWinScores[2][0] : null;

      // 构造同赔分析结果
      sameOddsAnalysisResult.value = {
        total_matches,
        home_wins,
        draws,
        away_wins,
        home_win_rate,
        draw_rate,
        away_win_rate,
        most_common_score,
        second_most_common_score,
        third_most_common_score,
        home_win_most_common_score,
        home_win_second_most_common_score,
        home_win_third_most_common_score,
        away_win_most_common_score,
        away_win_second_most_common_score,
        away_win_third_most_common_score
      }

      ElMessage.success('同赔分析查询成功')
    } else {
      sameOddsAnalysisResult.value = null
      matchDetailsData.value = []
      ElMessage.error(matchDetailsResponse.message || '获取比赛明细数据失败')
    }
  } catch (error) {
    console.error('查询同赔分析失败:', error)
    sameOddsAnalysisResult.value = null
    matchDetailsData.value = []
    ElMessage.error('查询同赔分析失败，请稍后重试')
  } finally {
    sameOddsAnalysisLoading.value = false
    matchDetailsLoading.value = false
  }
}
/*
    // 处理比赛明细数据
    if (matchDetailsResponse.code === 0 && matchDetailsResponse.data) {
      matchDetailsData.value = matchDetailsResponse.data
    } else {
      matchDetailsData.value = []
      ElMessage.error(matchDetailsResponse.message || '获取比赛明细数据失败')
    }
*/
// 查询队伍实力分析
async function fetchTeamStrengthAnalysis() {
  if (!currentMatchForAnalysis.value) {
    return
  }

  // 检查必要的参数是否存在
  const match = currentMatchForAnalysis.value
  if (!match.homeid || !match.awayid || !match.fid ) {
    console.warn('缺少必要的参数进行队伍实力分析:', {
      homeid: match.homeid,
      awayid: match.awayid
    })
    // 如果缺少必要参数，不执行队伍实力分析
    return
  }

  teamStrengthAnalysisLoading.value = true

  try {
    // 获取主队实力分析数据
    const homeRequestData = {
      teamid: match.homeid,
      fid: match.fid
    }

    // 获取客队实力分析数据
    const awayRequestData = {
      teamid: match.awayid,
      fid: match.fid
    }

    // 并行请求主队和客队的实力分析数据
    const [homeResponse, awayResponse] = await Promise.all([
      getTeamStrengthAnalysisApi(homeRequestData),
      getTeamStrengthAnalysisApi(awayRequestData)
    ])

    if (homeResponse.code === 0 && awayResponse.code === 0) {
      teamStrengthAnalysisData.value = {
        home: homeResponse.data,
        away: awayResponse.data
      }
    } else {
      const errorMessage = homeResponse.message || awayResponse.message || '获取队伍实力分析数据失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('查询队伍实力分析失败:', error)
    ElMessage.error('查询队伍实力分析失败，请稍后重试')
  } finally {
    teamStrengthAnalysisLoading.value = false
  }
}

// 查询球员实力分析
async function fetchPlayerStrengthAnalysis() {
  if (!currentMatchForAnalysis.value) {
    return
  }

  // 检查必要的参数是否存在
  const match = currentMatchForAnalysis.value
  if (!match.homeid || !match.awayid || !match.fid) {
    console.warn('缺少必要的参数进行球员实力分析:', {
      homeid: match.homeid,
      awayid: match.awayid,
      fid: match.fid
    })
    // 如果缺少必要参数，不执行球员实力分析
    return
  }

  playerStrengthAnalysisLoading.value = true

  try {
    // 获取主队球员实力分析数据
    const homeRequestData = {
      teamid: match.homeid,
      fid: match.fid
    }

    // 获取客队球员实力分析数据
    const awayRequestData = {
      teamid: match.awayid,
      fid: match.fid
    }

    // 并行请求主队和客队的球员实力分析数据
    const [homeResponse, awayResponse] = await Promise.all([
      getPlayerStrengthAnalysisApi(homeRequestData),
      getPlayerStrengthAnalysisApi(awayRequestData)
    ])

    if (homeResponse.code === 0 && awayResponse.code === 0) {
      playerStrengthAnalysisData.value = {
        home: homeResponse.data,  // 传递响应的数据部分
        away: awayResponse.data   // 传递响应的数据部分
      }
    } else {
      const errorMessage = homeResponse.message || awayResponse.message || '获取球员实力分析数据失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('查询球员实力分析失败:', error)
    ElMessage.error('查询球员实力分析失败，请稍后重试')
  } finally {
    playerStrengthAnalysisLoading.value = false
  }
}

// 查询爆冷分析
async function fetchColdPlayAnalysis() {
  if (!currentMatchForAnalysis.value) {
    return
  }

  // 检查必要的参数是否存在
  const match = currentMatchForAnalysis.value
  if (!match.homeid || !match.awayid || !match.matchtime || !match.season_id) {
    console.warn('缺少必要的参数进行爆冷分析:', {
      homeid: match.homeid,
      awayid: match.awayid,
      matchtime: match.matchtime,
      season_id: match.season_id
    })
    // 如果缺少必要参数，不执行爆冷分析
    return
  }

  coldPlayAnalysisLoading.value = true

  try {
    // 获取主队爆冷分析数据
    const homeRequestData = {
      teamid: match.homeid,
      match_date: match.matchtime ? match.matchtime.split('T')[0] : null,
      season_id: match.season_id
    }

    // 获取客队爆冷分析数据
    const awayRequestData = {
      teamid: match.awayid,
      match_date: match.matchtime ? match.matchtime.split('T')[0] : null,
      season_id: match.season_id
    }

    // 并行请求主队和客队的爆冷分析数据
    const [homeResponse, awayResponse] = await Promise.all([
      getColdPlayAnalysisStatsApi(homeRequestData),
      getColdPlayAnalysisStatsApi(awayRequestData)
    ])

    if (homeResponse.code === 0 && awayResponse.code === 0) {
      coldPlayAnalysisData.value = {
        home: homeResponse.data,
        away: awayResponse.data
      }
    } else {
      const errorMessage = homeResponse.message || awayResponse.message || '获取爆冷分析数据失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('查询爆冷分析失败:', error)
    ElMessage.error('查询爆冷分析失败，请稍后重试')
  } finally {
    coldPlayAnalysisLoading.value = false
  }
}

// 更新标签页标题
function updateTabTitle(newMatch: HistoricalSameOddsData) {
  if (newMatch && newMatch.homesxname && newMatch.awaysxname) {
    const homeScore = newMatch.homescore !== null ? newMatch.homescore : '-'
    const awayScore = newMatch.awayscore !== null ? newMatch.awayscore : '-'
    const title = `同赔分析-${newMatch.homesxname} ${homeScore} - ${awayScore} ${newMatch.awaysxname}`

    // 设置浏览器标题
    document.title = title

    // 更新 tags-view store 中的标题
    const visitedViews = tagsViewStore.visitedViews
    const currentRoutePath = route.path
    const index = visitedViews.findIndex(view => view.path === currentRoutePath)

    if (index !== -1) {
      // 更新 visitedViews 中的标题
      visitedViews[index].meta = {
        ...visitedViews[index].meta,
        title: title
      }
      // 触发响应式更新
      tagsViewStore.visitedViews = [...visitedViews]
    }
  }
}

// 监听currentMatchForAnalysis变化，动态更新路由标题
watch(currentMatchForAnalysis, (newMatch) => {
  if (newMatch && newMatch.homesxname && newMatch.awaysxname) {
    updateTabTitle(newMatch)
  }
}, { immediate: true })

// 监听originalValues变化，更新范围值
watch(originalValues, (newOriginalValues) => {
  if (newOriginalValues) {
    // 注意：originalValues只包含原始值，而rangeValues包含范围(min/max)
    // 这里只在组件挂载或原始值更新时设置默认范围
    if (!rangeValues.value || Object.keys(rangeValues.value).length === 0) {
      // 如果rangeValues还没有初始化，设置默认范围
      rangeValues.value = {
        homeInitialMin: newOriginalValues.homeInitial * 0.95,
        homeInitialMax: newOriginalValues.homeInitial * 1.05,
        drawInitialMin: newOriginalValues.drawInitial * 0.95,
        drawInitialMax: newOriginalValues.drawInitial * 1.05,
        awayInitialMin: newOriginalValues.awayInitial * 0.95,
        awayInitialMax: newOriginalValues.awayInitial * 1.05,

        homeFinalMin: newOriginalValues.homeFinal * 0.95,
        homeFinalMax: newOriginalValues.homeFinal * 1.05,
        drawFinalMin: newOriginalValues.drawFinal * 0.95,
        drawFinalMax: newOriginalValues.drawFinal * 1.05,
        awayFinalMin: newOriginalValues.awayFinal * 0.95,
        awayFinalMax: newOriginalValues.awayFinal * 1.05,

        probHomeInitialMin: newOriginalValues.probHomeInitial - 2,
        probHomeInitialMax: newOriginalValues.probHomeInitial + 2,
        probDrawInitialMin: newOriginalValues.probDrawInitial - 2,
        probDrawInitialMax: newOriginalValues.probDrawInitial + 2,
        probAwayInitialMin: newOriginalValues.probAwayInitial - 2,
        probAwayInitialMax: newOriginalValues.probAwayInitial + 2,

        probHomeFinalMin: newOriginalValues.probHomeFinal - 2,
        probHomeFinalMax: newOriginalValues.probHomeFinal + 2,
        probDrawFinalMin: newOriginalValues.probDrawFinal - 2,
        probDrawFinalMax: newOriginalValues.probDrawFinal + 2,
        probAwayFinalMin: newOriginalValues.probAwayFinal - 2,
        probAwayFinalMax: newOriginalValues.probAwayFinal + 2,

        returnRateInitialMin: newOriginalValues.returnRateInitial - 2,
        returnRateInitialMax: newOriginalValues.returnRateInitial + 2,
        returnRateFinalMin: newOriginalValues.returnRateFinal - 2,
        returnRateFinalMax: newOriginalValues.returnRateFinal + 2
      };
    }
  }
}, { immediate: true })

// 从URL参数中获取比赛数据
function getMatchFromUrlParams(): HistoricalSameOddsData | null {
  // 在 hash 路由模式下，需要从 hash 中提取查询参数
  const hash = window.location.hash
  const queryString = hash.includes('?') ? hash.split('?')[1] : ''
  const params = new URLSearchParams(queryString)

  // 检查必要参数是否存在
  const fid = params.get('fid')
  const homesxname = params.get('homesxname')
  const awaysxname = params.get('awaysxname')

  if (!fid || !homesxname || !awaysxname) {
    return null
  }

  return {
    fid: parseInt(fid) || null,
    event_name: params.get('event_name') || null,
    homesxname: homesxname,
    awaysxname: awaysxname,
    matchtime: params.get('matchtime') || null,
    homescore: params.get('homescore') ? parseInt(params.get('homescore')!) : null,
    awayscore: params.get('awayscore') ? parseInt(params.get('awayscore')!) : null,
    home_initial: parseFloat(params.get('home_initial') || '0') || null,
    draw_initial: parseFloat(params.get('draw_initial') || '0') || null,
    away_initial: parseFloat(params.get('away_initial') || '0') || null,
    home_final: parseFloat(params.get('home_final') || '0') || null,
    draw_final: parseFloat(params.get('draw_final') || '0') || null,
    away_final: parseFloat(params.get('away_final') || '0') || null,
    prob_home_initial: parseFloat(params.get('prob_home_initial') || '0') || null,
    prob_draw_initial: parseFloat(params.get('prob_draw_initial') || '0') || null,
    prob_away_initial: parseFloat(params.get('prob_away_initial') || '0') || null,
    prob_home_final: parseFloat(params.get('prob_home_final') || '0') || null,
    prob_draw_final: parseFloat(params.get('prob_draw_final') || '0') || null,
    prob_away_final: parseFloat(params.get('prob_away_final') || '0') || null,
    return_rate_initial: parseFloat(params.get('return_rate_initial') || '0') || null,
    return_rate_final: parseFloat(params.get('return_rate_final') || '0') || null,
    // 爆冷分析需要的字段
    season_id: params.get('season_id') ? parseInt(params.get('season_id')!) : null,
    homeid: params.get('homeid') ? parseInt(params.get('homeid')!) : null,
    awayid: params.get('awayid') ? parseInt(params.get('awayid')!) : null,
    order_num: params.get('order_num') || null,
    ownerdate: params.get('ownerdate') || null,
    home_avg_points: params.get('home_avg_points') ? parseFloat(params.get('home_avg_points')!) : null,
    away_avg_points: params.get('away_avg_points') ? parseFloat(params.get('away_avg_points')!) : null,
    signal_home_initial: params.get('signal_home_initial') ? parseFloat(params.get('signal_home_initial')!) : null,
    signal_draw_initial: params.get('signal_draw_initial') ? parseFloat(params.get('signal_draw_initial')!) : null,
    signal_away_initial: params.get('signal_away_initial') ? parseFloat(params.get('signal_away_initial')!) : null
  }
}

// 生命周期
onMounted(() => {
  // 优先从URL参数中获取比赛数据
  let matchData = getMatchFromUrlParams()

  // 如果URL参数中没有数据，尝试从store中获取
  if (!matchData) {
    matchData = currentMatchForAnalysis.value
  }

  if (!matchData) {
    ElMessage.error('缺少比赛数据')
    goBack()
    return
  }

  // 设置当前比赛数据
  currentMatchForAnalysis.value = matchData

  // 页面加载时自动查询爆冷分析数据
  fetchColdPlayAnalysis()

  // 页面加载时自动查询队伍实力分析数据
  fetchTeamStrengthAnalysis()

  // 页面加载时自动查询球员实力分析数据
  fetchPlayerStrengthAnalysis()
})

// 处理球员数据更新（删除行后）
function handlePlayerDataUpdate({ home, away }) {
  if (playerStrengthAnalysisData.value) {
    playerStrengthAnalysisData.value = {
      home: home,
      away: away
    }
  }
}
</script>

<style scoped>
.same-odds-analysis-page {
  padding: 20px;
}

.title-card {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.odds-range-card {
  margin-bottom: 1px;
}

.volatility-row {
  margin-bottom: 20px;
}

.volatility-control {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.volatility-info {
  margin-bottom: 10px;
  padding: 8px;
  background-color: #e3f2fd;
  border-radius: 4px;
  font-size: 12px;
}

.volatility-range {
  margin: 2px 0;
  color: #1976d2;
  font-weight: 500;
}

.volatility-slider {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 10px;
}

.volatility-stepper {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.volatility-label {
  font-size: 14px;
  color: #606266;
  min-width: 60px;
}

.volatility-value {
  font-size: 14px;
  font-weight: bold;
  color: #409eff;
  min-width: 40px;
  text-align: right;
}

.odds-range-item {
  display: flex;
  align-items: center;
  margin-bottom: 0px;
  padding: 0px 0;
}

.odds-label {
  width: 80px;
  font-size: 12px;
  color: #606266;
}

.odds-value {
  width: 60px;
  font-weight: bold;
  color: #303133;
  text-align: center;
}

.odds-range {
  flex: 1;
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.query-button-wrapper {
  text-align: center;
  margin-top: 0px;
  padding-top: 0px;
  /* border-top: 1px solid #ebeef5; */
}

.analysis-result-card {
  margin-top: 20px;
}

.analysis-result-content {
  padding: 10px 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.rate-row {
  margin-bottom: 20px;
}

.rate-item {
  text-align: center;
  padding: 15px;
  border-radius: 8px;
}

.rate-item.home {
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
}

.rate-item.draw {
  background-color: #fef3c7;
  border: 1px solid #fde68a;
}

.rate-item.away {
  background-color: #f0fdf4;
  border: 1px solid #bbf7d0;
}

.rate-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.rate-item.home .rate-value {
  color: #1e40af;
}

.rate-item.draw .rate-value {
  color: #92400e;
}

.rate-item.away .rate-value {
  color: #166534;
}

.rate-label {
  font-size: 14px;
  color: #606266;
}

.score-row {
  margin-bottom: 20px;
}

.score-item {
  text-align: center;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.score-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.team-strength-analysis-card {
  margin-top: 5px;
}

.team-strength-analysis-content {
  padding: 10px 0;
}

.cold-play-analysis-card {
  margin-top: 5px;
}

.team-analysis {
  padding: 10px;
}

.team-analysis.home {
  border-right: 1px solid #ebeef5;
}

.team-title {
  text-align: center;
  margin: 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.table-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cell-label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 2px;
}

.cell-value {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

.conversion-factor {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

/* 赔率显示样式 */
.odds-group {
  display: flex;
  gap: 8px;
}

.odds-item {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.odds-item.home {
  background-color: #f0f9ff;
  color: #1e40af;
}

.odds-item.draw {
  background-color: #fef3c7;
  color: #92400e;
}

.odds-item.away {
  background-color: #f0fdf4;
  color: #166534;
}

/* 积分和信号值范围输入样式 */
.range-inputs-row {
  margin-bottom: 5px;
}

.range-input-group {
  padding: 5px;
  background-color: #f8f9fa;
  border-radius: 2px;
  border: 1px solid #e9ecef;
  margin-bottom: 5px;
}

.range-input-group.compact {
  padding: 5px;
}

.range-input-group h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.range-input-group.compact h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  text-align: center;
}

.range-separator {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #606266;
}
</style>